package com.ideal.manage.esms.service.project;

import com.ideal.manage.esms.bean.DTO.PageDto;
import com.ideal.manage.esms.bean.project.EquipmentManage;
import com.ideal.manage.esms.bean.project.EquipmentMessageConf;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.project.EquipmentManageRepository;
import com.ideal.manage.esms.repository.project.EquipmentMessageConfRepository;
import com.ideal.manage.esms.util.ExportTextUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created By Dai On 2018/4/25
 * Remark: 工程配置 - 对象管理 - 设备管理 - 报文数据 Service
 */
@Service
public class EquipmentMessageConfService {
    private Logger logger = LoggerFactory.getLogger(EquipmentMessageConfService.class);

    @Autowired
    private EquipmentManageRepository equipmentManageRepository;

    @Autowired
    private EquipmentMessageConfRepository equipmentMessageConfRepository;

    /**
     * 工程配置 -> 对象管理 -> 设备管理 -> 查看报文数据列表
     *
     * @param pageNum
     * @param request
     * @param id
     * @return
     */
    public PageDto findAll(int pageNum, HttpServletRequest request, String id) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        List<SpecificationOperator> operators = new ArrayList<SpecificationOperator>() {{
            add(new SpecificationOperator("equipment.id", id, "EQ"));
        }};
        //增加删除标识的过滤
        MySpecification<EquipmentMessageConf> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 10, sort);
        Page<EquipmentMessageConf> page = equipmentMessageConfRepository.findAll(mySpecifications, pageable);
        //设置PageDto
        List<EquipmentMessageConf> parameters = page.getContent();
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(parameters);
        pageDto.setTotal(total);
        return pageDto;
    }

    /**
     * 查找对应的报文数据实体类
     *
     * @param id
     * @return
     */
    public EquipmentMessageConf findOne(String id) {
        return equipmentMessageConfRepository.findOne(id);
    }

    /**
     * 工程配置 -> 对象管理 -> 设备管理 -> 查看报文数据列表 -> 保存
     */
    public String saveMessage(String id, String equipment_id, String subjectName, String canId, String canLong,
                              String head, String dataType, String beginByte, String beginPosition, String endByte,
                              String endPosition, String offset, String multiple, String unit, String objId) {
        EquipmentManage equipmentManage = equipmentManageRepository.findOne(equipment_id);
        if (equipmentManage == null) {
            return "获取设备id失败";
        }
        EquipmentMessageConf equipmentMessageConf = equipmentMessageConfRepository.findOne(id);
        if (equipmentMessageConf == null) {
            equipmentMessageConf = new EquipmentMessageConf();
        }
        equipmentMessageConf.setEquipment(equipmentManage);
        equipmentMessageConf.setSubjectName(subjectName);
        equipmentMessageConf.setCanId(canId);
        equipmentMessageConf.setCanLong(canLong);
        equipmentMessageConf.setHead(head);
        equipmentMessageConf.setDataType(dataType);
        equipmentMessageConf.setBeginByte(beginByte);
        equipmentMessageConf.setBeginPosition(beginPosition);
        equipmentMessageConf.setEndByte(endByte);
        equipmentMessageConf.setEndPosition(endPosition);
        equipmentMessageConf.setOffset(offset);
        equipmentMessageConf.setMultiple(multiple);
        equipmentMessageConf.setUnit(unit);
        equipmentMessageConf.setObjId(objId);
        equipmentMessageConfRepository.save(equipmentMessageConf);
        return "保存成功";
    }

    /**
     * 工程配置 -> 对象管理 -> 设备管理 -> 查看报文数据列表 -> 删除
     *
     * @return
     */
    public void messageDelete(String[] ids) {
        List<EquipmentMessageConf> list = equipmentMessageConfRepository.findAll(Arrays.asList(ids));
        equipmentMessageConfRepository.delete(list);
    }

    /**
     * 工程配置 -> 对象管理 -> 设备管理 -> 查看报文数据列表 -> 导出
     *
     * @param response
     * @param id
     * @return
     */
    public void exportMessage(HttpServletResponse response, String id) {
        EquipmentManage equipmentManage = equipmentManageRepository.findOne(id);
        String str = "没有内容";
        List<EquipmentMessageConf> list = equipmentMessageConfRepository.findByEquipmentId(id);
        if (list.size() > 0) {
            str = "";
        }
        for (EquipmentMessageConf equipmentMessageConf : list) {
            str += equipmentMessageConf.getSubjectName() + "\t" +
                    equipmentMessageConf.getCanId() + "\t" +
                    equipmentMessageConf.getCanLong() + "\t" +
                    equipmentMessageConf.getHead() + "\t" +
                    equipmentMessageConf.getDataType() + "\t" +
                    equipmentMessageConf.getBeginByte() + "\t" +
                    equipmentMessageConf.getBeginPosition() + "\t" +
                    equipmentMessageConf.getEndByte() + "\t" +
                    equipmentMessageConf.getEndPosition() + "\t" +
                    equipmentMessageConf.getOffset() + "\t" +
                    equipmentMessageConf.getMultiple() + "\t" +
                    equipmentMessageConf.getUnit() + "\t" +
                    equipmentMessageConf.getObjId()
                    + "\n";
        }
        ExportTextUtil.writeToTxt(response, str, "导出报文数据列表_" + equipmentManage.getName());
        logger.info("导出报文数据列表_" + equipmentManage.getId() + "文件内容\n" + str);
    }

    /**
     * 工程配置 -> 对象管理 -> 设备管理 -> 查看报文数据列表 -> 导入
     *
     * @param file
     * @param equipment_id
     * @return
     */
    public String importMessage(MultipartFile file, String equipment_id) {
        if (file == null) {
            return "获取文件失败";
        }
        if (!file.getOriginalFilename().endsWith(".txt")) {
            return "请传入txt格式文件";
        }
        EquipmentManage equipmentManage = equipmentManageRepository.findOne(equipment_id);
        if (equipmentManage == null) {
            return "获取设备失败";
        }
        BufferedReader bufferedReader = null;
        // 数字的正则匹配
        String forInt = "[1-9]\\d*";
        String forDouble = "[1-9]\\d*\\.?\\d*";
        List<EquipmentMessageConf> list = new ArrayList<>();
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String readLine = "";
            // 所有的集合
            while (StringUtils.isNotBlank(readLine = bufferedReader.readLine())) {
                String[] info = readLine.split("\t");
                if (info.length < 13) {
                    return "文件内容格式有误，请检查文件内容";
                }
                if (!(Pattern.matches(forInt, info[2]) & Pattern.matches(forInt, info[5]) & Pattern.matches(forInt, info[6]) &
                        Pattern.matches(forInt, info[7]) & Pattern.matches(forInt, info[8]) & Pattern.matches(forInt, info[9]) &
                        Pattern.matches(forDouble, info[10]))) {
                    return "文件内容错误，无法解析";
                }
                EquipmentMessageConf equipmentMessageConf = new EquipmentMessageConf();
                equipmentMessageConf.setEquipment(equipmentManage);
                equipmentMessageConf.setSubjectName(info[0]);
                equipmentMessageConf.setCanId(info[1]);
                equipmentMessageConf.setCanLong(info[2]);
                equipmentMessageConf.setHead(info[3]);
                equipmentMessageConf.setDataType(info[4]);
                equipmentMessageConf.setBeginByte(info[5]);
                equipmentMessageConf.setBeginPosition(info[6]);
                equipmentMessageConf.setEndByte(info[7]);
                equipmentMessageConf.setEndPosition(info[8]);
                equipmentMessageConf.setOffset(info[9]);
                equipmentMessageConf.setMultiple(info[10]);
                equipmentMessageConf.setUnit(info[11]);
                equipmentMessageConf.setObjId(info[12]);
                list.add(equipmentMessageConf);
            }
            //走到这里都木有错的话就先删除老的，再放进来新的
            List<EquipmentMessageConf> deleteList = equipmentMessageConfRepository.findByEquipmentId(equipment_id);
            equipmentMessageConfRepository.delete(deleteList);
            equipmentMessageConfRepository.save(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "导入成功";
    }
}
